const express = require('express');
const pool = require('../pool');
const router = express.Router();

router.post('/login',(req,res)=>{
  let user = req.body.user;
  let upwd = req.body.upwd;
  let sql = 'select uid from igou_user where (email=? or phone=?) and upwd=md5(?)';
  pool.query(sql,[user,user,upwd],(err,result)=>{
    if(err) throw err;
    if(result.length>0){
      res.json({code:1,...result[0]})
    }else {
      res.json({code:-1,msg:'用户名或密码错误'})
    }
  })
});

router.post('/register',(req,res)=>{
  let { email, phone, upwd } = req.body;
  pool.getConnection((err,conn)=>{
    conn.query('select uid from igou_user where email=?',[email],(err,result)=>{
      if(err) throw err;
      if(result.length>0){
        res.json({code:-1,msg:'该邮箱已注册'});
        return;
      }

      let sql = 'insert into igou_user(email,phone,upwd) values (?,?,md5(?))';
      conn.query(sql,[email,phone,upwd],(err,result)=>{
        if(err) throw err;
        if(result.affectedRows>0)
          res.json({
            code: 1,
            msg: '注册成功',
            uid: result.insertId,
            user: req.body.email || req.body.phone
          });
        else
          res.json({code:-1,msg:'出错啦'});
        conn.release();
      })
    })
  })
});

module.exports = router;